package top.jidanmian.android.mqttdemo.ui.mqtt

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import top.jidanmian.android.mqttdemo.mqtt.MyMqttConn
import javax.inject.Inject

data class MqttViewState(
    val topic: String = "",
    val message: String = "",
    // 临时设置
    val testInfo: String = "",
)

@HiltViewModel
class MqttViewModel @Inject constructor(
    private val myMqttConn: MyMqttConn
) : ViewModel() {
    private var _uiState = MutableStateFlow(MqttViewState())
    var uiState: StateFlow<MqttViewState> = _uiState.asStateFlow()

    fun updateTopic(topic: String) {
        _uiState.update { currentState ->
            currentState.copy(
                topic = topic
            )
        }
    }

    fun updateMessage(message: String) {
        _uiState.update { currentState ->
            currentState.copy(
                message = message
            )
        }
    }

    fun clean() {
        _uiState.value = MqttViewState()
    }

    fun send() {
        if (_uiState.value.topic.isBlank()) return
        if (_uiState.value.message.isBlank()) return

        viewModelScope.launch {
            myMqttConn.publish(topic = _uiState.value.topic, msg = _uiState.value.message)
        }

        _uiState.update { currentState ->
            currentState.copy(
                testInfo = "Topic: ${currentState.topic.trim()}, Message: ${currentState.message.trim()}"
            )
        }
    }

    fun subscribe() {
        if (_uiState.value.topic.isBlank()) return
        myMqttConn.subscribe(topic = _uiState.value.topic)
        _uiState.update { currentState ->
            currentState.copy(
                testInfo = "订阅Topic: ${currentState.topic.trim()}"
            )
        }
    }
}

